/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package doc2db.interfaces.action.createTable;

import doc2db.Keey;
import doc2db.UserProp;
import doc2db.fileWorker.FileBeginer;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

/**
 *
 * @author yura
 *
 * ┌─────────────────────────────────────────────────────┐
 * │ table_schema.table_name                             │
 * ├───────────┬───────────┬─────────────┬───────────────┤
 * │column_name│column_name│             │column_name│   │
 * │ [ name  ] │ [ name  ] │             │ [ name  ] │   │
 * │           │           │             │           │   │
 * │ data_type │ data_type │             │ data_type │   │
 * │ [ type ▼] │ [ type ▼] │  .  .  .    │ [ type ▼] │   │
 * │           │           │             │           │   │
 * │ x data    │ x data    │             │ x data    │┌─┐│
 * │ [ data  ] │ [ data  ] │             │ [ data  ] ││+││
 * │           │           │             │           │└─┘│
 * │ x NotNull │ x NotNull │             │ x NotNull │┌─┐│
 * │ x Unique  │ x Unique  │             │ x Unique  ││-││
 * │ xIncrement│ xIncrement│             │ xIncrement│└─┘│
 * ├───────────┴───────────┴─────────────┴───────────┴───┤
 * │                                                     │
 * │                                   cancel   ok       │
 * └─────────────────────────────────────────────────────┘
 */
public class DbClientDialogCreateTable  extends JDialog{
    private boolean isPl = false;
    
    private Container c = this.getContentPane();
    JButton ok = new JButton("<html><p>ok", new  ImageIcon(
            FileBeginer.resurse_resurseFolderMenu+Keey.sp + "save.png"));
    private JButton cancel = new JButton(new AbstractAction("<html><p>отмена",
            new ImageIcon(FileBeginer.resurse_resurseFolderMenu+Keey.sp+"cancel.png")){
        public void actionPerformed(ActionEvent e) {
            setVisible(false);
        }
    });
    private JButton addBut = new JButton(new AbstractAction("<html><p color=blue><b><pre>+"){
        public void actionPerformed(ActionEvent e) {
            list.add(new TableColumn());
            initPaneList();
            myResize();
        }
    });
    private JButton remBut = new JButton(new AbstractAction("<html><p color=blue><b><pre>-"){
        public void actionPerformed(ActionEvent e) {
            list.remove(list.size() - 1);
            initPaneList();
            myResize();
        }
    });
    private JTextField tableName = new JTextField("table_name", 36);
    private List<TableColumn> list = new ArrayList<TableColumn>();
    private JPanel listPane = new JPanel(new BorderLayout());
    private JLabel l = new JLabel("primary key :");
    private JTextField t = new JTextField("", 24);


    public DbClientDialogCreateTable(JFrame f){
        super(f, true);
        this.initFrame();
        this.setMyFont();
        this.initComponent();
    }

    private void initFrame(){
        setTitle("менеджер БД");
        setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
        setResizable(true);
        Toolkit kit = Toolkit.getDefaultToolkit();
        Dimension screnSize = kit.getScreenSize();
        int screanHeight = screnSize.height ;
        int screanWidth = screnSize.width ;
        setSize(600, 380);
        setLocation((screanWidth / 2 - 300), (screanHeight / 2 - 175));
    }
    
    private void initComponent() {
        JPanel p = new JPanel(new BorderLayout());
        this.initPaneList();
        p.add(new JScrollPane(listPane), BorderLayout.CENTER);

        Box h = Box.createVerticalBox();
        h.add(Box.createGlue());
        h.add(addBut);
        h.add(Box.createVerticalStrut(6));
        h.add(remBut);
        h.add(Box.createVerticalStrut(6));
        p.add(h, BorderLayout.EAST);

        JPanel p1 = new JPanel();
        p1.add(tableName);
        p.add(p1, BorderLayout.NORTH);

        Box b1 = Box.createHorizontalBox();
        b1.add(Box.createGlue());
        b1.add(ok);
        b1.add(Box.createHorizontalStrut(4));
        b1.add(cancel);
        b1.add(Box.createHorizontalStrut(4));
        Box b2 = Box.createHorizontalBox();
        b2.add(Box.createHorizontalStrut(4));
        b2.add(l);
        b2.add(Box.createHorizontalStrut(2));
        b2.add(t);
        b2.add(Box.createGlue());
        Box h2 = Box.createVerticalBox();
        h2.add(b2);
        h2.add(b1);
        p.add(h2, BorderLayout.SOUTH);

        c.add(p, BorderLayout.CENTER);
    }

    public String getTableSql(){
        StringBuffer tableSql = new StringBuffer();
        tableSql.append("CREATE TABLE \"" + tableName.getText() + "\" ( ");
        for (int i = 0; i < list.size(); i++) {
            tableSql.append(list.get(i).getText());
            if((i+1) < list.size())
            tableSql.append(",");
        }
        String s = t.getText();
        if(! s.equals("")){
            for (TableColumn tableColumn : list) {
                String s2 = tableColumn.getColName();
                if(s.equals("" + s2)){
                    tableSql.append(", PRIMARY KEY (\"");
                    tableSql.append(s);
                    tableSql.append("\") ");
                    break;
                }
            }
        }
        tableSql.append(") ;");
        return tableSql.toString();
    }

    public String getAdditionalInformation(){
        StringBuffer retStr = new StringBuffer();
            retStr.append("");

        for (TableColumn tableColumn : list) {
            if(! tableColumn.isAutoIncrement())
                continue;

            String seq = tableName.getText().replaceAll(" ", "") + "_"
                    + tableColumn.getColName().replaceAll(" ", "") + "_seq";
            seq = seq.toLowerCase();

            retStr.append(" CREATE SEQUENCE \"");
            retStr.append(seq);
            retStr.append("\" ; \n");

            retStr.append(" ALTER TABLE \"");
            retStr.append(tableName.getText());
            retStr.append("\" ALTER COLUMN \"");
            retStr.append(tableColumn.getColName());
            retStr.append("\" SET DEFAULT NEXTVAL(\'");
            retStr.append(seq);
            retStr.append("\'); \n");

            retStr.append(" UPDATE \"");
            retStr.append(tableName.getText());
            retStr.append("\" SET \"");
            retStr.append(tableColumn.getColName());
            retStr.append("\" = NEXTVAL(\'");
            retStr.append(seq);
            retStr.append("\'); \n\n");
        }

        return retStr.toString();
    }

    private void initPaneList() {
        Box b = Box.createHorizontalBox();
        b.add(Box.createHorizontalStrut(2));
        if (list.size() < 1) {
            list.add(new TableColumn());
        }
        for (TableColumn tC : list) {
            b.add(tC);
            b.add(Box.createHorizontalStrut(2));
        }
        listPane.removeAll();
        listPane.add(b, BorderLayout.CENTER);
    }
    
    private void setMyFont(){
        tableName.setFont(UserProp.paneFont);
        ok.setFont(UserProp.paneFont);
        cancel.setFont(UserProp.paneFont);
        l.setFont(UserProp.paneFont);
        t.setFont(UserProp.textFont);
        tableName.setPreferredSize(new Dimension(tableName.getPreferredSize().width, 30));
        ok.setMaximumSize(cancel.getPreferredSize());
        cancel.setMaximumSize(cancel.getPreferredSize());
        addBut.setMaximumSize(addBut.getPreferredSize());
        remBut.setMaximumSize(remBut.getPreferredSize());
        t.setMaximumSize(t.getPreferredSize());

        t.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                JPopupMenu m = new JPopupMenu();
                for (TableColumn tC : list) {
                    final String s = tC.getColName();
                    JMenuItem select = new JMenuItem(new AbstractAction(s) {
                        public void actionPerformed(ActionEvent e) {
                            t.setText(s);
                        }
                    });
                    select.setFont(UserProp.menuFont);
                    m.add(select);
                }
                m.show(e.getComponent(), e.getX(), e.getY());
            }
        });
        t.setEditable(false);
    }

    public String getTableName(){
        return tableName.getText();
    }

    private void myResize() {
        if (isPl) {
            setSize(getSize().width + 1, getSize().height + 1);
        } else {
            setSize(getSize().width - 1, getSize().height - 1);
        }
        isPl = !isPl;
    }

}
